import '../request/base_request.dart';
import 'hi_net_adapter.dart';
import 'hi_net_error.dart';
import 'hi_net_response.dart';

class HiNet {
  HiNet._();

  static HiNet? _instance;

  static HiNet instance() {
    _instance ??= HiNet._();
    return _instance!;
  }

  Future fire(BaseRequest request) async {
    HiNetResponse? response;
    dynamic error;
    try {
      response = await send(request);
    } on HiNetError catch (e) {
      response = e.data;
      error = e;
      print("网络请求HiNetError: ${e.message}");
    } catch (e) {
      //其它异常
      error = e;
      print("网络请求error: ${e.toString()}");
    }
    if (response == null) {
      print("网络请求出错：$error");
    }
    var result = response?.data;

    var status = response?.statusCode;
    switch (status) {
      case 200:
        print("网络请求成功：$result");
        return result;
      case 401:
        print("抛除异常 NeedLogin");
        throw NeedLogin();
      case 403:
        print("抛除异常 NeedAuth");
        throw NeedAuth(message: result.toString(), data: result);
      default:
        print("抛除异常 HiNetError");
        throw HiNetError(status ?? -1, response?.statusMessage ?? "", data: result);
    }
  }

  Future<HiNetResponse<T>> send<T>(BaseRequest request) async {
    ///使用Dio发送请求
    HiNetAdapter adapter = DioAdapter();
    return adapter.send(request);
  }
}
